import { apiService } from "./api/api-service.js";
import { AlertHelper } from "./utils/alert-helper.js";
import { assembleUploadData } from "./utils/upload-helper.js";

// 模板列表（从background.js获取）
let templates = [];
// 存储当前商户信息
let currentMerchantInfo = null;

// 日期处理函数
function formatDate(date) {
  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0");
  const dd = String(date.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

function getLastSevenDays() {
  const end = new Date();
  end.setDate(end.getDate() - 1);
  const start = new Date(end);
  start.setDate(end.getDate() - 6);
  return {
    start: formatDate(start),
    end: formatDate(end),
    label: `${formatDate(start)} ~ ${formatDate(end)} (近七日)`,
  };
}

function getLastFourWeeks() {
  const weeks = [];
  const today = new Date();
  today.setDate(today.getDate() - 1); // 从昨天开始计算

  // 获取当前是周几（0-6，0表示周日）
  const currentDay = today.getDay();

  // 计算到最近一个完整周的结束日期（周日）的天数
  const daysToLastSunday = currentDay;

  // 获取最近一个完整周的结束日期
  const lastSunday = new Date(today);
  lastSunday.setDate(today.getDate() - daysToLastSunday);

  // 获取最近4个完整的自然周
  for (let i = 0; i < 4; i++) {
    const end = new Date(lastSunday);
    end.setDate(lastSunday.getDate() - i * 7);
    const start = new Date(end);
    start.setDate(end.getDate() - 6);

    let label;
    if (i === 0) {
      label = "上周";
    } else {
      label = `前${i}周`;
    }

    weeks.push({
      start: formatDate(start),
      end: formatDate(end),
      label: `${formatDate(start)} ~ ${formatDate(end)} (${label})`,
    });
  }

  return weeks;
}

// 获取模板配置
function loadTemplates() {
  return new Promise((resolve) => {
    chrome.runtime.sendMessage({ action: "getTemplates" }, function (response) {
      if (response && response.templates) {
        templates = response.templates;
        initTemplates();
        resolve();
      }
    });
  });
}

const templateSelect = document.getElementById("templateSelect");
const merchantInfo = document.getElementById("merchantInfo");
const periodSelect = document.getElementById("periodSelect");
const extractBtn = document.getElementById("extractBtn");
const stopBtn = document.getElementById("stopBtn");
const exportBtn = document.getElementById("exportBtn");
const resultDiv = document.getElementById("result");
const copyBtn = document.getElementById("copyBtn");
const clearBtn = document.getElementById("clearBtn");
const buttonGroup = document.querySelector(".button-group");

// 直接获取静态HTML中的抓取范围相关元素
const scopeContainer = document.querySelector('.scope-container');
const autoExportCheckbox = document.getElementById('autoExport');

// 获取抓取范围
function getScope() {
  return document.querySelector('input[name="scope"]:checked').value;
}

// 获取自动导出状态
function getAutoExport() {
  return autoExportCheckbox.checked;
}

// 更新自动导出复选框状态
function updateAutoExportState() {
  const scopeAll = document.querySelector('input[name="scope"][value="all"]');
  if (scopeAll.checked) {
    autoExportCheckbox.checked = true;
    autoExportCheckbox.disabled = true;
    // 保存自动导出状态
    chrome.storage.local.set({ autoExport: true });
  } else {
    autoExportCheckbox.disabled = false;
    // 保存自动导出状态
    chrome.storage.local.set({ autoExport: autoExportCheckbox.checked });
  }
}

// 使用 Promise 包装消息发送
const sendMessageToContentScript = (tabId, message) => {
  return new Promise((resolve, reject) => {
    chrome.tabs.sendMessage(tabId, message, (response) => {
      if (chrome.runtime.lastError) {
        // 将错误对象转换为更易读的格式
        const error = {
          message: chrome.runtime.lastError.message,
          stack: chrome.runtime.lastError.stack,
          name: chrome.runtime.lastError.name
        };
        console.error("发送消息失败:[message]", message, "[error]", error.name, error.message, error.stack);
        reject(error);
      } else {
        resolve(response);
      }
    });
  });
};

// 获取商户信息
async function getMerchantInfo() {
  try {
    // 通过 background.js 获取商户信息
    const response = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ action: 'getMerchantInfo' }, (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response);
        }
      });
    });

    if (response && response.success) {
      let { merchantId, merchantName } = response.data;
      // 保存商户信息
      // 将字符串出现的( 和 ) 替换为（）
      merchantName = merchantName.replace(/\(/g, '（').replace(/\)/g, '）');
      currentMerchantInfo = { merchantId, merchantName };
      // 换行
      merchantInfo.innerHTML = `商户名称: ${merchantName}<br>商户ID: ${merchantId}`;
      // 保存状态
      saveState();
      return { merchantId, merchantName };
    } else {
      const errorMsg = response?.error || "无法获取商户信息";
      console.error("获取商户信息失败:", errorMsg);
      throw new Error(errorMsg);
    }
  } catch (error) {
    console.error("获取商户信息失败:", error);
    // 显示更详细的错误信息
    const errorMessage = error.message || "未知错误";
    const errorDetails = error.stack ? `\n详细信息: ${error.stack}` : "";
    merchantInfo.textContent = `获取商户信息失败: ${errorMessage}${errorDetails}`;
    currentMerchantInfo = null;
    throw error; // 向上传递错误，让调用者处理
  }
}

// 保存状态到 storage
function saveState() {
  const templateId = templateSelect.value;
  const template = templates.find((t) => t.id === templateId);
  const state = {
    lastExtracted: window._lastExtracted,
    resultHtml: resultDiv.innerHTML,
    period: periodSelect.value,
    merchantInfo: currentMerchantInfo  // 添加商户信息
  };
  if (template && Array.isArray(template.scopes) && template.scopes.length > 0) {
    state.scope = getScope();
  }
  chrome.storage.local.set({ [`pluginState_${templateId}`]: state });
}

// 从 storage 恢复状态
function restoreState() {
  const templateId = templateSelect.value;
  const template = templates.find((t) => t.id === templateId);
  chrome.storage.local.get([`pluginState_${templateId}`, 'autoExport'], function (result) {
    const state = result[`pluginState_${templateId}`];
    if (state) {
      if (state.lastExtracted) {
        window._lastExtracted = state.lastExtracted;
        resultDiv.innerHTML = state.resultHtml;
        buttonGroup.style.display = "flex";
        extractBtn.classList.add("success");
        exportBtn.classList.add("success");
      }
      if (state.period) {
        periodSelect.value = state.period;
      }
      if (template && Array.isArray(template.scopes) && template.scopes.length > 0 && state.scope) {
        document.querySelector(`input[name=\"scope\"][value=\"${state.scope}\"]`).checked = true;
        // 根据scope更新自动导出状态
        updateAutoExportState();
      }
      // 修复商户信息显示
      if (state.merchantInfo) {
        currentMerchantInfo = state.merchantInfo;
        const { merchantName, merchantId } = state.merchantInfo;
        if (merchantName && merchantId) {
          merchantInfo.innerHTML = `商户名称: ${merchantName}<br>商户ID: ${merchantId}`;
          merchantInfo.parentElement.style.display = "block";  // 确保商户信息区域显示
        }
      }
    }

    // 恢复自动导出状态
    if (result.autoExport !== undefined) {
      autoExportCheckbox.checked = result.autoExport;
      // 如果当前是全部抓取，则禁用复选框
      const scopeAll = document.querySelector('input[name="scope"][value="all"]');
      if (scopeAll && scopeAll.checked) {
        autoExportCheckbox.disabled = true;
      }
    }
  });
}

// 清除状态
function clearState() {
  const templateId = templateSelect.value;
  window._lastExtracted = null;
  resultDiv.innerHTML = '请先选择模板并点击"开始抓取"';
  buttonGroup.style.display = "none";
  extractBtn.classList.remove("success");
  exportBtn.classList.remove("success");
  chrome.storage.local.remove([`pluginState_${templateId}`]);
}

// 更新按钮状态
function updateButtonState(isRunning) {
  if (isRunning) {
    extractBtn.style.display = "none";
    stopBtn.style.display = "block";
    exportBtn.disabled = true;
  } else {
    extractBtn.style.display = "block";
    stopBtn.style.display = "none";
    // 只有在非自动导出模式下才启用导出按钮
    exportBtn.disabled = getAutoExport();
  }
}

// 初始化模板下拉框
function initTemplates() {
  templates.forEach((tpl) => {
    const opt = document.createElement("option");
    opt.value = tpl.id;
    opt.textContent = tpl.label;
    templateSelect.appendChild(opt);
  });

  // 初始化后立即更新样式
  updateTemplateStyle(templateSelect.value);
  updateScopeOptions();
}

// 根据模板显示/隐藏scope单选框，并设置默认值
function updateScopeOptions() {
  const template = templates.find((t) => t.id === templateSelect.value);
  const scopeOptions = scopeContainer.querySelector('.scope-options');
  const divider = scopeContainer.querySelector('.divider');
  const radios = scopeContainer.querySelectorAll('input[name="scope"]');
  if (template && Array.isArray(template.scopes) && template.scopes.length > 0) {
    // 显示scope选项和分隔符
    if (scopeOptions) scopeOptions.style.display = '';
    if (divider) divider.style.display = '';
    // 只保留模板允许的选项
    radios.forEach(radio => {
      if (template.scopes.includes(radio.value)) {
        radio.parentElement.style.display = '';
      } else {
        radio.parentElement.style.display = 'none';
      }
    });
    // 设置默认选中
    let defaultScope = template.defaultScope || template.scopes[0];
    const defaultRadio = scopeContainer.querySelector(`input[name="scope"][value="${defaultScope}"]`);
    if (defaultRadio) defaultRadio.checked = true;
    scopeContainer.style.display = "flex";
  } else {
    // 只隐藏scope选项和分隔符，自动导出始终显示
    if (scopeOptions) scopeOptions.style.display = 'none';
    if (divider) divider.style.display = 'none';
    scopeContainer.style.display = "flex";
  }
}

// 格式化显示数据
function formatData(data) {
  if (!Array.isArray(data)) return "无效的数据格式";

  let html = '<div class="data-container">';

  data.forEach((group) => {
    html += `<div class="group">
      <h3 class="group-title">${group.groupTitle}</h3>
      <div class="cards-count">包含 ${group.cards.length} 个指标</div>
      ${
        group.cards.length > 0
          ? '<div class="cards-list">'
          : '<div class="no-cards">暂无指标</div>'
      }
    `;

    if (group.cards.length > 0) {
      group.cards.forEach((card) => {
        html += `<div class="card">
          <div class="card-name">${card.label}</div>
          <div class="card-value">${card.value}</div>
          ${Object.entries(card)
            .filter(([key]) => key !== "label" && key !== "value")
            .map(
              ([key, value]) =>
                `<div class="card-change">${key}: ${value}</div>`
            )
            .join("")}
        </div>`;
      });
      html += "</div>";
    }

    html += "</div>";
  });

  html += "</div>";
  return html;
}

// 复制到剪贴板
async function copyToClipboard() {
  const data = window._lastExtracted;
  if (!data) return;

  try {
    await navigator.clipboard.writeText(JSON.stringify(data, null, 2));
    copyBtn.textContent = "已复制";
    copyBtn.classList.add("copied");
    setTimeout(() => {
      copyBtn.textContent = "复制";
      copyBtn.classList.remove("copied");
    }, 2000);
  } catch (err) {
    console.error("复制失败:", err);
    alert("复制失败: " + err.message);
  }
}

// 更新界面显示
function updateUI(state) {
  if (state.isRunning) {
    resultDiv.innerHTML = '<div class="loading">抓取中...</div>';
    extractBtn.classList.remove("success");
    exportBtn.classList.remove("success");
    buttonGroup.style.display = "none";
    updateButtonState(true);
  } else if (state.error) {
    resultDiv.innerHTML = `<div class="error">抓取失败：${state.error}</div>`;
    extractBtn.classList.remove("success");
    exportBtn.classList.remove("success");
    buttonGroup.style.display = "none";
    updateButtonState(false);
  } else if (state.result) {
    window._lastExtracted = state.result;
    resultDiv.innerHTML = formatData(state.result);
    buttonGroup.style.display = "flex";
    extractBtn.classList.add("success");
    exportBtn.classList.add("success");
    updateButtonState(false);
    saveState();
  }
}

// 抓取指标数据
async function extractMetric() {
  clearState();
  const templateId = templateSelect.value;
  const period = periodSelect.value;
  const template = templates.find((t) => t.id === templateId);
  let scope = 'current'; // 默认值
  if (template && Array.isArray(template.scopes) && template.scopes.length > 0) {
    scope = getScope();
  }

  try {
    await getMerchantInfo();
  } catch (error) {
    showError(`获取商户信息失败: ${error.message}`);
    return;
  }

  let startDate = "",
    endDate = "";
  const parts = period.split("|");
  if (parts.length === 3) {
    startDate = parts[1];
    endDate = parts[2];
  }
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (startDate && endDate) {
    await new Promise((resolve) => {
      chrome.tabs.sendMessage(
        tab.id,
        {
          action: "setCustomDateRange",
          startDate,
          endDate,
          periodType: period.startsWith('week') ? 'natural_week' : 'last_7_days'
        },
        function (response) {
          resolve();
        }
      );
    });
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
  updateButtonState(true);
  // 传递 autoExport 参数和 scope 参数
  const msg = {
    action: "startExtraction",
    template: templateId,
    period: period,
    autoExport: getAutoExport(),
    scope: scope  // 添加 scope 参数
  };
  chrome.runtime.sendMessage(msg);
  window._customDateRange = { startDate, endDate };
}

// 停止抓取
function stopExtraction() {
  chrome.runtime.sendMessage({
    action: "stopExtraction",
    template: templateSelect.value
  });
  clearState();
  updateButtonState(false);
}

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'batchExtracted') {
    handleBatchUpload(request.data, request.batchIndex, request.isLastBatch);
    return;
  }
  if (
    request.action === "extractionStatus" ||
    request.action === "extractionComplete"
  ) {
    updateUI(request.state);
  }
});

// 自动导出逻辑
async function autoExportAfterExtract(data) {
  const currentTemplate = templates.find((t) => t.id === templateSelect.value);
  if (!currentMerchantInfo || !currentTemplate) return;
  const uploadData = assembleUploadData({
    merchantInfo: currentMerchantInfo,
    currentTemplate,
    period: periodSelect.value,
    data,
  });
  let groupCount = Array.isArray(data) ? data.length : 0;
  let cardCount = Array.isArray(data) ? data.reduce((sum, g) => sum + (g.cards?.length || 0), 0) : 0;
  try {
    const result = await apiService.uploadMerchantData(uploadData);
    if (result.success) {
      AlertHelper.success(`自动导出成功，分组数：${groupCount}，卡片数：${cardCount}`);
    } else {
      AlertHelper.error(`自动导出失败，分组数：${groupCount}，卡片数：${cardCount}`);
    }
  } catch (error) {
    AlertHelper.error(`自动导出异常，分组数：${groupCount}，卡片数：${cardCount}`);
  }
}

// 导出为JSON
async function exportJSON() {
  const data = window._lastExtracted;
  if (!data) {
    AlertHelper.error("请先抓取数据");
    return;
  }

  if (!currentMerchantInfo) {
    const errorMsg = "未获取到商户信息，请确保页面已正确加载";
    await apiService.copyErrorToClipboard(errorMsg);
    AlertHelper.error(errorMsg + "\n(错误信息已复制到剪贴板)");
    return;
  }

  const currentTemplate = templates.find((t) => t.id === templateSelect.value);
  if (!currentTemplate) {
    const errorMsg = "未找到当前选中的模板信息";
    await apiService.copyErrorToClipboard(errorMsg);
    AlertHelper.error(errorMsg + "\n(错误信息已复制到剪贴板)");
    return;
  }

  exportBtn.disabled = true;
  exportBtn.textContent = "导出中...";

  try {
    // 使用公用方法组装上传数据
    const uploadData = assembleUploadData({
      merchantInfo: currentMerchantInfo,
      currentTemplate,
      period: periodSelect.value,
      data,
    });

    const result = await apiService.uploadMerchantData(uploadData);

    if (result.success) {
      AlertHelper.success("数据上传成功");
      console.log("上传成功:", result.data);
    } else {
      const errorMsg = "上传失败: " + result.error;
      await apiService.copyErrorToClipboard(errorMsg);
      AlertHelper.error(errorMsg + "\n(错误信息已复制到剪贴板)");
      console.error("上传失败:", result.error);
    }
  } catch (error) {
    const errorMsg = "上传失败: " + error.message;
    await apiService.copyErrorToClipboard(errorMsg);
    AlertHelper.error(errorMsg + "\n(错误信息已复制到剪贴板)");
    console.error("上传失败:", error);
  } finally {
    exportBtn.disabled = false;
    exportBtn.textContent = "导出JSON";
  }
}

// 检查当前页面并自动选择模板
async function autoSelectTemplate() {
  try {
    // 获取当前标签页
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true,
    });
    if (!tab || !tab.url) {
      templateSelect.value = "none";
      updateTemplateStyle("none");
      return;
    }

    // 解析URL
    const url = new URL(tab.url);
    console.log("当前页面域名:", url.hostname);

    // 查找匹配的模板
    const matchedTemplate = templates.find((tpl) => {
      if (!tpl.matchPattern) return false;

      // 直接判断URL中是否包含配置的域名
      const isMatch = url.hostname.includes(tpl.matchPattern);
      console.log("域名匹配结果:", {
        hostname: url.hostname,
        pattern: tpl.matchPattern,
        isMatch,
      });

      return isMatch;
    });

    if (matchedTemplate) {
      templateSelect.value = matchedTemplate.id;
      updateTemplateStyle(matchedTemplate.id);
      console.log("自动选择模板:", matchedTemplate.label);
    } else {
      templateSelect.value = "none";
      updateTemplateStyle("none");
      console.log("未找到匹配的模板，使用默认选项");
    }
  } catch (error) {
    console.error("自动选择模板失败:", error);
    templateSelect.value = "none";
    updateTemplateStyle("none");
  }
}

// 更新模板选择框样式
function updateTemplateStyle(templateId) {
  const template = templates.find((t) => t.id === templateId);
  if (template && template.isWarning) {
    templateSelect.classList.add("warning");
    console.log("应用警示样式");
    // 隐藏商户信息和筛选周期
    merchantInfo.parentElement.style.display = "none";
    periodSelect.parentElement.style.display = "none";
  } else {
    templateSelect.classList.remove("warning");
    console.log("移除警示样式");
    // 显示商户信息和筛选周期
    merchantInfo.parentElement.style.display = "block";
    periodSelect.parentElement.style.display = "flex";
  }
}

// 监听抓取范围变化
document.querySelectorAll('input[name="scope"]').forEach(radio => {
  radio.addEventListener('change', () => {
    updateAutoExportState();
    updateButtonState(false);
  });
});

// 监听自动导出复选框变化
autoExportCheckbox.addEventListener('change', () => {
  updateButtonState(false);
  // 保存自动导出状态
  chrome.storage.local.set({ autoExport: autoExportCheckbox.checked });
});

// 初始化
document.addEventListener("DOMContentLoaded", async () => {
  try {
    await loadTemplates(); // 等待模板加载完成
    await autoSelectTemplate(); // 自动选择模板

    // 初始化周期选项
    const lastSevenDays = getLastSevenDays();
    const lastFourWeeks = getLastFourWeeks();

    // 清空现有选项
    periodSelect.innerHTML = "";

    // 创建所有选项
    const options = [];

    // 创建近七日选项
    const sevenDaysOption = document.createElement("option");
    sevenDaysOption.value = `last7days|${lastSevenDays.start}|${lastSevenDays.end}`;
    sevenDaysOption.textContent = lastSevenDays.label;
    options.push(sevenDaysOption);

    // 创建最近四周选项
    lastFourWeeks.forEach((week) => {
      const option = document.createElement("option");
      option.value = `week|${week.start}|${week.end}`;
      option.textContent = week.label;
      options.push(option);
    });

    // 一次性添加所有选项
    options.forEach((option) => periodSelect.appendChild(option));

    // 设置默认选中近七日
    periodSelect.value = `last7days|${lastSevenDays.start}|${lastSevenDays.end}`;

    // 初始化时根据模板状态控制显示
    updateTemplateStyle(templateSelect.value);

    // 新增：初始化抓取范围单选框，确保首次加载时显示正确
    updateScopeOptions();

    // 恢复之前保存的状态
    restoreState();

    // 监听模板选择变化
    templateSelect.addEventListener("change", () => {
      updateTemplateStyle(templateSelect.value);
      clearState(); // 切换模板时清除当前状态
      restoreState(); // 恢复新选择模板的状态
      updateScopeOptions(); // 新增：切换模板时更新scope单选框
    });

    // 监听周期选择变化
    periodSelect.addEventListener("change", () => {
      saveState(); // 保存周期选择
    });

    // 绑定按钮事件
    extractBtn.onclick = extractMetric;
    stopBtn.onclick = stopExtraction;
    exportBtn.onclick = exportJSON;
    copyBtn.onclick = copyToClipboard;
    clearBtn.onclick = clearState;

    // 初始化时移除成功状态的按钮样式
    extractBtn.classList.remove("success");
    exportBtn.classList.remove("success");
    updateButtonState(false);

    // 主题切换功能
    const themeToggle = document.getElementById("theme-toggle");

    // 从存储中读取主题设置
    chrome.storage.local.get(["theme"], function (result) {
      if (result.theme === "dark") {
        document.documentElement.setAttribute("data-theme", "dark");
        themeToggle.checked = true;
      }
    });

    // 监听主题切换
    themeToggle.addEventListener("change", function () {
      if (this.checked) {
        document.documentElement.setAttribute("data-theme", "dark");
        chrome.storage.local.set({ theme: "dark" });
      } else {
        document.documentElement.removeAttribute("data-theme");
        chrome.storage.local.set({ theme: "light" });
      }
    });

    // 获取当前提取状态，带上当前模板id
    chrome.runtime.sendMessage({ action: "getExtractionStatus", template: templateSelect.value });
  } catch (error) {
    console.error("初始化失败:", error);
  }
});

async function handleBatchUpload(data, batchIndex, isLastBatch) {
  // 检查是否开启自动导出
  if (!getAutoExport()) {
    console.log('自动导出未开启，跳过上传');
    return;
  }
  
  const currentTemplate = templates.find((t) => t.id === templateSelect.value);
  if (!currentMerchantInfo || !currentTemplate) return;
  const uploadData = assembleUploadData({
    merchantInfo: currentMerchantInfo,
    currentTemplate,
    period: periodSelect.value,
    data,
  });
  let groupCount = Array.isArray(data) ? data.length : 0;
  let cardCount = Array.isArray(data) ? data.reduce((sum, g) => sum + (g.cards?.length || 0), 0) : 0;
  try {
    const result = await apiService.uploadMerchantData(uploadData);
    if (result.success) {
      AlertHelper.success(`第${batchIndex + 1}批上传成功，分组数：${groupCount}，卡片数：${cardCount}`);
    } else {
      AlertHelper.error(`第${batchIndex + 1}批上传失败，分组数：${groupCount}，卡片数：${cardCount}`);
    }
  } catch (error) {
    AlertHelper.error(`第${batchIndex + 1}批上传异常，分组数：${groupCount}，卡片数：${cardCount}`);
  }
}
